﻿using System;
using HttpApiGateway.Interface;
using RpcClient.Interface;
using RpcHelper;

namespace HttpApiGateway.Config
{

    public class CrossDomainConfig : ICrossDomainConfig
    {
        private static DefCrossConfig _Config;
        static CrossDomainConfig()
        {
            RpcClient.RpcClient.Config.AddRefreshEvent(_Refresh);
        }

        private static void _Refresh(IConfigServer config, string name)
        {
            if (name == string.Empty || name == "gateway:cross" || name.StartsWith("gateway:cross:"))
            {
                _Config = RpcClient.RpcClient.Config.GetConfigVal<DefCrossConfig>("gateway:cross", new DefCrossConfig());
            }
        }
        /// <summary>
        /// 允许跨域
        /// </summary>
        public bool AllowCredentials
        {
            get => _Config.AllowCredentials;
        }

        /// <summary>
        /// 跨域限定允许访问来源
        /// </summary>
        public string[] AllowUrlReferrer
        {
            get => _Config.AllowUrlReferrer;
        }
        /// <summary>
        /// 跨域限定头部
        /// </summary>
        public string AllowHead
        {
            get => _Config.AllowHead;
        }
        /// <summary>
        /// 有效时间
        /// </summary>
        public string MaxAge
        {
            get => _Config.MaxAge;
        }

        /// <summary>
        /// 允许的请求方式 ,号分隔
        /// </summary>
        public string Method
        {
            get => _Config.Method;
        }

        public bool IsEnable => _Config.IsEnable;

        public bool CheckUrlReferrer(Uri referrer)
        {
            if (!_Config.AllowCredentials)
            {
                return false;
            }
            return _Config.AllowUrlReferrer == null || _Config.AllowUrlReferrer.IsExists(a => a == referrer.Authority || referrer.Authority.EndsWith(a));
        }
    }
}
